﻿using Leo.Blog.ViewModel.SysModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Leo.Blog.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            string moduleId = HttpContext.Request.QueryString["ModuleID"] ?? "";
            ViewBag.ModuleID = moduleId;
            ViewBag.UserName = UserName;
            return View();
        }
        public ActionResult Main()
        {
            return View();
        }
        /// <summary>
        /// 获取生成菜单的菜单项
        /// </summary>
        /// <param name="moduleID">初始为0，即顶层节点父ID为0</param>
        /// <param name="randomCode"></param>
        /// <returns></returns>
        public ActionResult GetTopModules(int moduleID, string randomCode)
        {
            UserAccountVM accountVM = Session["UserAccount"] as UserAccountVM;
            List<UserModule> listModule = accountVM.Modules;
            //第一层模组
            SysModuleTree moduleTree = new SysModuleTree();
            GetTree(moduleTree,listModule,moduleID);
            return Json(moduleTree.Children,JsonRequestBehavior.AllowGet);
        }
        private void GetTree(SysModuleTree rootNode, List<UserModule> listModules, int parentId = 0)
        {
            var listParent = GetChildrenByParentId(listModules, parentId);
            foreach (var item in listParent)
            {
                var listChild = GetChildrenByParentId(listModules, item.ModuleId);
                SysModuleTree tn = new SysModuleTree();
                tn.Module = item;
                if (listChild != null)
                {
                    GetTree(tn, listModules, item.ModuleId);
                }
                rootNode.Children.Add(tn);
            }
        }
        private List<UserModule> GetChildrenByParentId(List<UserModule> listModules, int parentId = 0)
        {
            var userModule = listModules.Where(m => m.ParentModuleId == parentId).OrderBy(m=>m.SortNo).ToList();
            return userModule;
        }
    }
}